<?php


namespace app\service\model;


use app\service\Y;

class CouponModel extends BaseModel
{
    protected $table = 'coupon';


    /**
     * 用户领取记录
     * @return \think\model\relation\HasMany
     */
    public function memberCoupon(): \think\model\relation\HasMany
    {
        return $this->hasMany(MemberCouponModel::class, 'coupon_id', 'id');
    }
    /**
     * 保存数据
     * @param $param
     * @param $id
     * @return bool|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function saveData($param, $id) {
        if ($id > 0) {
            if (self::where('title', '=', $param['title'])
                ->where('id', '<>', $id)
                ->where(function ($query) {
                    $query->where('is_permanent_validity', '=', 0)
                        ->whereOr(function ($query) {
                        $query->where('start_time', '<', date('Y-m-d H:i:s'))->where('end_time', '>', date('Y-m-d H:i:s'));
                    });
                })
                ->find()) {
                return Y::error('优惠券名称已存在');
            }

            $data = self::find($id);
            if (!$data) {
                return Y::error('参数错误');
            }
            $data->save($param);
        } else {
            if (self::where('title', '=', $param['title'])
                ->where(function ($query) {
                    $query->where('is_permanent_validity', '=', 0)
                        ->whereOr(function ($query) {
                            $query->where('start_time', '<', date('Y-m-d H:i:s'))->where('end_time', '>', date('Y-m-d H:i:s'));
                        });
                })
                ->find()) {
                return Y::error('优惠券名称已存在');
            }
            self::create($param);
        }
        return Y::success([], '保存成功');
    }
}